package com.example.demo.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class ChatService {

    // 使用单例模式来管理 OkHttpClient 实例，避免重复创建
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .build();

    private static final String URL = "https://qianfan.baidubce.com/v2/app/conversation/runs";
    private static final String AUTH_TOKEN = "Bearer bce-v3/ALTAK-dDQqVx4tToYfhO43SfFi9/998aff0b3ed01872fb45399a990ab8283195cd1f";

    private static final Logger logger = LoggerFactory.getLogger(ChatService.class);

    /**
     * 发送消息到 AI，并返回响应
     *
     * @param query           用户输入的消息
     * @param conversationId  会话 ID
     * @return AI 的答复
     * @throws IOException 如果请求失败，抛出 IOException
     */
    public String sendMessage(String query, String conversationId) throws IOException {
        // 设置请求内容
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        String jsonBody = String.format(
                "{\"app_id\":\"c70093fb-ca59-4c72-be5b-46a1907b15ba\",\"query\":\"%s\",\"conversation_id\":\"%s\",\"stream\":false}",
                query, conversationId);

        RequestBody body = RequestBody.create(mediaType, jsonBody);

        // 创建请求
        Request request = new Request.Builder()
                .url(URL)
                .post(body)
                .addHeader("Content-Type", mediaType.toString())
                .addHeader("X-Appbuilder-Authorization", AUTH_TOKEN)
                .build();

        // 执行请求并获取响应
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                // 获取响应内容
                String responseBody = response.body().string();

                // 打印调试日志：响应的完整内容
                logger.info("API Response: {}", responseBody);

                // 使用 Jackson 解析 JSON 响应并提取 "answer" 字段
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(responseBody);

                // 提取 "answer" 字段，处理可能的空值或 null
                JsonNode answerNode = rootNode.path("answer");
                String answer = answerNode.isNull() ? "" : answerNode.asText();

                // 返回答复内容，如果为空则返回默认消息
                return answer.isEmpty() ? "未能提取 AI 回复内容。" : answer;
            } else {
                // 如果请求不成功，抛出异常并记录详细错误信息
                int responseCode = response.code();
                String errorMessage = String.format("Failed to get a successful response from the server. HTTP status code: %d", responseCode);
                logger.error(errorMessage);
                throw new IOException(errorMessage);
            }
        } catch (Exception e) {
            // 记录异常信息并重新抛出 IOException
            logger.error("Error during API request: ", e);
            throw new IOException("Error during API request: " + e.getMessage(), e);
        }
    }
}